package com.meepo.sdk.component.observer

import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.lang.Exception

/**
 * @author
 *
 * @date  2020/11/2 1:37 PM
 * @version 1.0
 */
object ObserverManager {

    fun <T> applyFunc(func: (param: Any) -> T, param: Any): Observable<T> {
        return Observable.create(ObservableOnSubscribe<T> { emitter ->
            try {
                val rsp = func(param)
                if (rsp != null) {
                    emitter.onNext(rsp)
                } else {
                    emitter.onError(NullRspError())
                }
            } catch (e: Exception) {
                emitter.onError(e)
            }
        })
            .applySchedulers()

    }


    fun <T> applyFunc(func: () -> T): Observable<T> {
        return Observable.create { emitter ->
            try {
                val rsp = func()
                if (rsp != null) {
                    emitter.onNext(rsp)
                } else {
                    emitter.onError(NullRspError())
                }

            } catch (e: Exception) {
                emitter.onError(e)
            }
        }
    }

    fun <T> Observable<T>.applyObserver(observer: Observer<T>) {
        return subscribe(observer)
    }

    fun <T> Observable<T>.applySchedulers(): Observable<T> {
        return subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
    }
}